// @ts-nocheck
import {axios_request} from "@/api/milliaAxios";
import {ElMessage} from "element-plus";
import {ref} from "vue";
import {sleep} from "@/static/Login_Register/register";
import {useUserStore} from '@/stores/userStore';
import router from "@/router";



export const loginForm = {
    user: '',
    password: '',
}

// 显示密码
export const lo_pwdVisible = ref(false);
export const lo_eyeVisible = ref(false);

export const pwdSwitch = () => {
    lo_pwdVisible.value = !lo_pwdVisible.value
}

// 显示小眼睛
export const eyeSwitch = async () => {
    await sleep(300);
    lo_eyeVisible.value = true
}

// 登录请求
const user_error = ref(false);
const password_error = ref(false);

export function userLogin() {
    const userStore = useUserStore()

    return async () => {
        if (user_error.value || password_error.value) {
            return ElMessage.warning('用户名、电话号码或密码格式有误，请重新输入')
        } else {
            const res = await axios_request('/api/user/login/', JSON.stringify(loginForm), 'post')
            console.log("POST请求返回的数据：" + res);
            console.log(res);
            if (res.status == 200) {
                // 存储JWT到localStorage
                if (res.data.access_token || res.data.csrf_token) {
                     await userStore.login(res.data.access_token, res.data.csrf_token, res.data.user_id);
                    ElMessage.success(res.data.msg)
                    await sleep(1000);
                    // 实现登录跳转
                    await router.push({name: 'Home'})
                } else {
                    ElMessage.warning('登录失败')
                    await sleep(1000);
                    window.location.reload();
                }
            } else {
                ElMessage.warning("登录失败：" + res.data.msg)
            }
        }
    };
}


// 校验数据
export const check_user = () => {
    const reg_tel = /^1[3-9]\d{9}$/;  // 电话号码匹配规则
    const reg_name = /^[A-Za-z][A-Za-z0-9_]{4,19}$/;  // 用户名匹配规则：以字母开头，长度在5~20之间，只能包含字母、数字和下划线

    if(reg_tel.test(loginForm.user) && loginForm.user.length == 11) {  // 登录方式：电话号码
        user_error.value = false;
    }else user_error.value = !(reg_name.test(loginForm.user) && loginForm.user.length < 21);
}

export const check_pwd = () => {
    lo_eyeVisible.value = false;
    const reg = /^[A-Za-z][A-Za-z0-9_.*#/]{5,17}$/;
    password_error.value = !reg.test(loginForm.password) || loginForm.password.length > 16;
}
